package com.imay.live.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;

import com.imay.live.R;
import com.imay.live.helper.LocationHelper;
import com.imay.live.helper.PreferenceHelper;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.AppUtil;
import com.imay.live.utils.PermissionUtil;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.yanzhenjie.permission.Rationale;
import com.yanzhenjie.permission.RationaleListener;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * MainActivity权限控制部分
 * Created by Administrator on 2017/8/9 0009.
 */

public abstract class BasePermissionActivity extends BaseCocosActivity implements LocationHelper.OnLocationListener {
    private static final int REQUEST_CODE_PERMISSION_MULTI = 101;

    public static final int REQUEST_CODE_SETTING = 300;

    protected boolean isPermissing = false;

    /**
     * 初始化Permission
     */
    protected void initPermission() {
        List<String> deniedPermissions = new ArrayList<>(Arrays.asList(Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.READ_PHONE_STATE));
        if (AndPermission.hasAlwaysDeniedPermission(BasePermissionActivity.this, deniedPermissions)) {
            isPermissing = true;
            AndPermission.with(this)
                    .requestCode(REQUEST_CODE_PERMISSION_MULTI)
                    .permission(Permission.LOCATION, Permission.STORAGE, new String[]{Manifest.permission.READ_PHONE_STATE})
                    .callback(permissionListener)
                    // rationale作用是：用户拒绝一次权限，再次申请时先征求用户同意，再打开授权对话框；
                    // 这样避免用户勾选不再提示，导致以后无法申请权限。
                    // 你也可以不设置。
                    .rationale(new RationaleListener() {
                        @Override
                        public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                            // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                            AndPermission.rationaleDialog(BasePermissionActivity.this, rationale).show();
                        }
                    })
                    .start();
        }
    }

    /**
     * 回调监听。
     */
    private PermissionListener permissionListener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
            isPermissing = false;
            switch (requestCode) {
                case REQUEST_CODE_PERMISSION_MULTI: {
                    appAcivation();
                    if (grantPermissions.contains(Manifest.permission.ACCESS_FINE_LOCATION)
                            && grantPermissions.contains(Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        getLocation();
                    }
                    break;
                }
            }
        }

        @Override
        public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {
            isPermissing = false;
            switch (requestCode) {
                case REQUEST_CODE_PERMISSION_MULTI: {
                    appAcivation();
                    if (PermissionUtil.selfPermissionGranted(BasePermissionActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
                            && PermissionUtil.selfPermissionGranted(BasePermissionActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        getLocation();
                    }
                    break;
                }
            }

            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(BasePermissionActivity.this, deniedPermissions)) {
                // 第二种：用自定义的提示语。
                AndPermission.defaultSettingDialog(BasePermissionActivity.this, REQUEST_CODE_SETTING)
                        .setTitle(R.string.permission_permission_title)
                        .setMessage(R.string.permission_permission)
                        .setPositiveButton(R.string.permission_button_setting)
                        .show();
            }
        }
    };

    // 初始激活App
    private void appAcivation() {
        if (!PreferenceHelper.getInstance().getAppActivation()) {
            PreferenceHelper.getInstance().saveAppActivation();
            String mac = AppUtil.getLocalMacAddress(getApplicationContext());
            String imei = AppUtil.generateDeviceId(getApplicationContext());
            String ip = AppUtil.getLocalIpAddress();
            String isp = AppUtil.getIsp(getApplicationContext());
            String channel = AppUtil.getChannel(getApplicationContext());
            ProtoRequestHelper.task(ProtoHttpFactory.requestAppActivation(mac, imei, ip, isp, channel)).request(null);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case REQUEST_CODE_SETTING: {
                appAcivation();
                if (PermissionUtil.selfPermissionGranted(this, Manifest.permission.ACCESS_FINE_LOCATION)
                        && PermissionUtil.selfPermissionGranted(this, Manifest.permission.ACCESS_COARSE_LOCATION)) {
                    getLocation();
                }
                break;
            }
        }
    }

    //显示开启定位状态
    protected void getLocation() {
        LocationHelper.getInstance().getLocation(this);
    }

    @Override
    public void onLocation(String city, double latitude, double longitude) {
        LocationHelper.getInstance().setCity(city);
        LocationHelper.getInstance().setLatitude(latitude);
        LocationHelper.getInstance().setLongitude(longitude);
    }
}
